package com.itasura.guava.Concurrency;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.*;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;

/**
 * @author sailor wang
 * @date 2018/10/30 5:16 PM
 * @description
 */
@Slf4j
public class AsyncFuntionSample implements AsyncFunction<Integer, String> {

    private ConcurrentMap<Integer, String> map = Maps.newConcurrentMap();
    private ListeningExecutorService listeningExecutorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());

    @Override
    public ListenableFuture<String> apply(Integer input) throws Exception {
        if (map.containsKey(input)) {
            SettableFuture<String> settableFuture = SettableFuture.create();
            log.info("get from cache");
            settableFuture.set(map.get(input));
            return settableFuture;
        }
        return listeningExecutorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                String result = SimpleService.visitDb();
                map.putIfAbsent(1, result);
                return result;
            }
        });
    }
}